package com.tarry.io.file.archive;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Objects;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Slf4j
public class FileCustomer implements Runnable{

    private final FileInfo fileInfo;
    private final String resourcePath;
    private final String targetPath;

    public FileCustomer(FileInfo fileInfo,
                        String resourcePath,
                        String targetPath) {
        this.fileInfo = fileInfo;
        this.resourcePath = resourcePath;
        this.targetPath = targetPath;
    }

    /**
     *
     * @param fileInfo
     */
    @SneakyThrows
    private void process(FileInfo fileInfo) {
        // 做两件事
        // 非压缩文件搬移
        if (FileDecompressUtil.isNotCompressFile(fileInfo.getType())){
            String parentPath = fileInfo.getParentPath();
            String tmpDir = targetPath +
                    File.separator +
                    parentPath.substring(resourcePath.length());
            Path path = Paths.get(tmpDir);
            if (!path.toFile().exists()) {
                Files.createDirectories(path);
            }
            String targetFileName = tmpDir +
                    File.separator +
                    fileInfo.getFileName();
            try (OutputStream outputStream = new FileOutputStream(targetFileName)) {
                Files.copy(fileInfo.getPath(), outputStream);
            }
        }else { // 文件解压到指定目录，
            FileDecompressUtil.decompress(fileInfo, targetPath);
        }
    }

    @Override
    public void run() {
        process(fileInfo);
    }
}
